// +----------------------------------------------------------------------
// | Manong.Cloud [ 领酷码农云 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020 http://www.manong.cloud All rights reserved.
// +----------------------------------------------------------------------
// | Author: 稻草人 <qinuoyun@qq.com>
// +----------------------------------------------------------------------
// | Member: 围棋 飘逸者 Loumt Silence24
// +----------------------------------------------------------------------

/* Arguments
 * list of hostnames (you need to create folders in static directory with the same names) - required
 * path to your static directory - required
 * path to default folder (in case if none of hostnames matched this one will be used) - not required
*/

export default (hostnames, static_dir, default_dir = '') => {
  return async (ctx, next) => {
    try {
      // Use default hostname if no matches
      const hostname = hostnames[ctx.hostname] ? hostnames[ctx.hostname] : default_dir
      // Compose path to static folder using hostname (must be the same as hostname)

      if (hostname && (ctx.request.url === "/" || ctx.request.url === "/login")) {
        ctx.redirect(hostname)
      }

      return await next()
    } catch (e) {
      ctx.throw(e.status || 500, e.message)
    }
  }
}
